package example.customer.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import example.customer.Customer;
import example.customer.service.CustomerService;

@Controller
public class CustomerController {
	@Autowired
	CustomerService customerService;
	
	@RequestMapping(value="customer/customerList", method=RequestMethod.GET)
	public ModelAndView getCustomers() {
		return new ModelAndView("customer.customerList","customers", customerService.getAllCustomers());
	}
	
	@RequestMapping(value="customer/addCustomerForm", method=RequestMethod.GET)
	public ModelAndView getAddCustomerForm(@ModelAttribute Customer customer) {
		return new ModelAndView("customer.addCustomerForm");
	}
	
	@RequestMapping(value="customer/addCustomer", method=RequestMethod.POST)
	public ModelAndView addCustomer(@ModelAttribute @Valid Customer customer, BindingResult result) {
		if (result.hasErrors()) return new ModelAndView("customer.addCustomerForm");
		String id = customerService.addCustomer(customer);
		System.out.println(id);
		return new ModelAndView("customer.addCustomerSuccess","lastName",customer.getLastName());
	}
}
